package org.cweili.rayminder.util

import groovy.json.JsonBuilder
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.math.NumberUtils
import org.cweili.rayminder.domain.Html
import org.h2.tools.Server
/**
 *
 * @author Cweili
 * @version 2013年8月5日 上午11:11:24
 *
 */
class Utils {

	static final String MSG_ERROR = 'error'
	static final String MSG_INFO = 'info'
	static final String MSG_SUCCESS = 'success'
	static final String MSG_DANGER = 'danger'
	static int id = 0

	static error(Exception e) {
		def sb = new StringBuilder('<h2>您的').append(Global.APP_NAME).append('傲娇了 ')
				.append('<a href="mailto:3weili@gmail.com" class="btn btn-info btn-large">联系Cweili</a></h2>')
				.append('<h4>错误信息:</h4><h5>').append(e).append('</h5>')
		e.stackTrace.each {
			sb.append(it).append('<br />')
		}
		new Html(title: "${Global.APP_NAME}傲娇了", content: sb).toString().getBytes(Global.CHARSET)
	}

	static String formatDate(Date date) {
		date.format(Global.DATE_FORMART)
	}

	static String formatTimeInMillis(long timeInMillis) {
		formatDate(new Date(time: timeInMillis))
	}

	static String getHome() {
		def home = Utils.protectionDomain.codeSource.location.path
		StringUtils.substringBeforeLast(home, '/')
	}

	static byte[] getResource(String path) {
		Utils.getResourceAsStream('/res/' + path)?.bytes
	}

	synchronized static int generateId() {
		int time = System.currentTimeMillis() >>> 6
		if (id < time) {
			id = time
		} else {
			++id
		}
	}

	static int intval(String str, int min = 0) {
		int i = NumberUtils.toInt(str)
		if (i < min) {
			return min
		}
		i
	}

	static message(type, msg, error = null) {
		json([type: type, message: msg, error: error])
	}

	static json(obj) {
		new JsonBuilder(obj).toString()
	}

	static openUrl(url) {
		Server.openBrowser("http://localhost:${Global.APP_PORT}${Global.APP_CONTEXT_PATH}${url}")
	}

	static quit() {
		Global.WEB_SERVER?.stop()
		System.exit(0)
	}

}
